package gavdi.dk.data;

import gavdi.dk.model.User;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DAOUser {

  // Database fields
  private SQLiteDatabase database;
  private MySQLiteHelper dbHelper;
  private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
      MySQLiteHelper.COLUMN_NAME };

  public DAOUser(Context context) {
    dbHelper = new MySQLiteHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public void createUser(User user) {
    open();
	ContentValues values = new ContentValues();
    
    values.put(MySQLiteHelper.COLUMN_ID, user.getUserID());
    values.put(MySQLiteHelper.COLUMN_NAME, user.getName());


    long l = database.insert(MySQLiteHelper.TABLE_USER, null,
        values);
    close();
	
  }

  public void deleteUser(User User) {
    String id = User.getUserID();
    database.delete(MySQLiteHelper.TABLE_USER, MySQLiteHelper.COLUMN_ID
        + " = " + "\""+id+"\"", null);
  }

  public User getUser(String userID) {
open();
    Cursor cursor = database.query(MySQLiteHelper.TABLE_USER,
        allColumns, MySQLiteHelper.COLUMN_ID + "="+"\""+userID+"\"", null, null, null, null);
    

        cursor.moveToFirst();
        
        User user = cursorToUser(cursor);
       
      // Make sure to close the cursor
      cursor.close();
      
close();
  
    return user;

    
  }
  public List<User> getAllUsers() {
	  open();
	    List<User> users = new ArrayList<User>();

	    Cursor cursor = database.query(MySQLiteHelper.TABLE_USER,
	        allColumns, null, null, null, null, null);

	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	    	User user = cursorToUser(cursor);
	    	users.add(user);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    close();
	    return users;
	  }
  public boolean exists(String userID){
	  boolean res = false;
	  open();
	  Cursor cursor = 	database.query(MySQLiteHelper.TABLE_USER,
		        		new String[]{MySQLiteHelper.COLUMN_ID}, 
		        		MySQLiteHelper.COLUMN_ID+"="+"\""+userID+"\"", null, null, null, null);
	  res = cursor.moveToFirst();
	  cursor.close();
	  close();
	  return res;
  }


  private User cursorToUser(Cursor cursor) {
	  User user = new User(cursor.getString(0), cursor.getString(1));
    return user;
  }
} 